package com.zy.service;

import com.zy.dao.UserMapper;
import com.zy.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 张宇
 * @date 2021/7/26 22:23
 */
@Service
public class UserService
{

    @Autowired
    private UserMapper userMapper;

    /**
     * 通过用户名和密码查找用户
     */
    public User findUserByUsernameAndPassword(String username, String password)
    {
        return userMapper.findUserByUsernameAndPassword(username,password);
    }

    /**
     * 通过id查找用户
     * @param id
     * @return
     */
    public User findUserById(int id)
    {
        return userMapper.findUserById(id);
    }

    /**
     * 通过id修改用户头像
     * @param id
     * @param headImg
     */
    public void upDateHeadImgById(int id, String headImg)
    {
        userMapper.upDateHeadImgById(id,headImg);
    }

    /**
     * 通过userName查找用户
     * @param username
     * @return
     */
    public User findUserByUserName(String username)
    {
        return userMapper.findUserByUserName(username);
    }

    /**
     * 查找用户列表
     * @param user
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Map<String,Object> findUserList(User user, int pageNo, int pageSize)
    {
        List<User> list = userMapper.findUserList(user);
        List<User> data = list.stream().skip((pageNo - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("data",data);
        map.put("pagesTotalCount",list.size());
        map.put("pageTotal",data.size());
        return map;
    }

    /**
     * 新增用户
     * @param user
     */
    public Map<String,Object> addUser(User user)
    {
        Map<String,Object> map = new HashMap<>();
        if(findUserByUserName(user.getUsername()) != null)
        {
            map.put("msg","用户已存在!");
            map.put("code",104);
        }
        else
        {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            userMapper.addUser(user);
            map.put("msg","添加成功!");
            map.put("code",200);
        }
        return map;
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    public int deleteUser(int id)
    {
        return userMapper.deleteUser(id);
    }

}
